<template>
  <div class="filter-panel">
    <div class="panel-header">
      <h4>筛选器</h4>
      <el-button size="small" @click="addFilter">添加筛选器</el-button>
    </div>
    
    <div class="filter-list">
      <div v-for="filter in filters" :key="filter.id" class="filter-item">
        <div class="filter-header">
          <span class="filter-field">{{ getFieldLabel(filter.field) }}</span>
          <el-button 
            size="small" 
            type="danger" 
            text 
            @click="removeFilter(filter.id)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
        
        <div class="filter-content">
          <!-- 文本类型筛选 -->
          <div v-if="getFieldType(filter.field) === 'string'" class="filter-controls">
            <el-select 
              v-model="filter.operator" 
              size="small" 
              style="width: 100px; margin-bottom: 8px;"
              @change="updateFilter(filter)">
              <el-option label="等于" value="equals" />
              <el-option label="包含" value="contains" />
              <el-option label="不等于" value="not_equals" />
            </el-select>
            
            <el-input 
              v-model="filter.value" 
              size="small" 
              placeholder="输入筛选值"
              @input="updateFilter(filter)" />
          </div>
          
          <!-- 数值类型筛选 -->
          <div v-else-if="getFieldType(filter.field) === 'number'" class="filter-controls">
            <el-select 
              v-model="filter.operator" 
              size="small" 
              style="width: 100px; margin-bottom: 8px;"
              @change="updateFilter(filter)">
              <el-option label="等于" value="equals" />
              <el-option label="大于" value="greater" />
              <el-option label="小于" value="less" />
              <el-option label="大于等于" value="greater_equal" />
              <el-option label="小于等于" value="less_equal" />
            </el-select>
            
            <el-input-number 
              v-model="filter.value" 
              size="small" 
              style="width: 100%;"
              @change="updateFilter(filter)" />
          </div>
          
          <!-- 日期类型筛选 -->
          <div v-else-if="getFieldType(filter.field) === 'date'" class="filter-controls">
            <el-select 
              v-model="filter.operator" 
              size="small" 
              style="width: 100px; margin-bottom: 8px;"
              @change="updateFilter(filter)">
              <el-option label="等于" value="equals" />
              <el-option label="之后" value="after" />
              <el-option label="之前" value="before" />
            </el-select>
            
            <el-date-picker
              v-model="filter.value"
              type="date"
              size="small"
              style="width: 100%;"
              placeholder="选择日期"
              @change="updateFilter(filter)" />
          </div>
          
          <!-- 多选筛选 -->
          <div class="filter-values">
            <div class="values-header">
              <span>可选值:</span>
              <el-button 
                size="small" 
                text 
                @click="toggleSelectAll(filter)">
                {{ isAllSelected(filter) ? '取消全选' : '全选' }}
              </el-button>
            </div>
            
            <div class="values-list">
              <el-checkbox-group 
                v-model="filter.selectedValues" 
                @change="updateFilter(filter)">
                <el-checkbox 
                  v-for="value in getUniqueValues(filter.field)" 
                  :key="value" 
                  :label="value"
                  size="small">
                  {{ formatValue(value, filter.field) }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="!filters.length" class="empty-state">
        <el-icon size="32" color="#c0c4cc"><Filter /></el-icon>
        <p>暂无筛选器</p>
        <p>点击上方按钮添加筛选器</p>
      </div>
    </div>
    
    <!-- 筛选器操作 -->
    <div v-if="filters.length" class="filter-actions">
      <el-button size="small" @click="clearAllFilters">清除所有</el-button>
      <el-button size="small" type="primary" @click="applyFilters">应用筛选</el-button>
    </div>
  </div>
  
  <!-- 添加筛选器对话框 -->
  <el-dialog 
    v-model="showAddDialog" 
    title="添加筛选器" 
    width="400px">
    <el-form :model="newFilter" label-width="80px">
      <el-form-item label="字段">
        <el-select v-model="newFilter.field" placeholder="选择字段">
          <el-option 
            v-for="field in availableFields"
            :key="field.id"
            :label="field.name"
            :value="field.id" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="confirmAddFilter">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useTableStore } from '../stores/tableStore'
import { Delete, Filter } from '@element-plus/icons-vue'

// 使用store
const tableStore = useTableStore()

// 响应式数据
const showAddDialog = ref(false)
const newFilter = ref({
  field: ''
})

// 计算属性
const filters = computed(() => tableStore.filters)
const availableFields = computed(() => tableStore.fields)

// 方法
const addFilter = () => {
  newFilter.value = { field: '' }
  showAddDialog.value = true
}

const confirmAddFilter = () => {
  if (!newFilter.value.field) return
  
  const field = availableFields.value.find(f => f.id === newFilter.value.field)
  if (!field) return
  
  const filter = {
    field: newFilter.value.field,
    operator: getDefaultOperator(field.type),
    value: '',
    selectedValues: []
  }
  
  // 初始化多选值
  const uniqueValues = getUniqueValues(newFilter.value.field)
  filter.selectedValues = [...uniqueValues]
  
  tableStore.addFilter(filter)
  showAddDialog.value = false
}

const removeFilter = (filterId) => {
  tableStore.removeFilter(filterId)
}

const updateFilter = (filter) => {
  // 筛选器已经通过响应式数据自动更新
  // 这里可以添加额外的逻辑，比如保存筛选器状态
  console.log('筛选器已更新:', filter)
}

const getFieldLabel = (fieldId) => {
  const field = availableFields.value.find(f => f.id === fieldId)
  return field ? field.name : fieldId
}

const getFieldType = (fieldId) => {
  const field = availableFields.value.find(f => f.id === fieldId)
  return field ? field.type : 'string'
}

const getDefaultOperator = (fieldType) => {
  switch (fieldType) {
    case 'number':
      return 'equals'
    case 'date':
      return 'equals'
    default:
      return 'contains'
  }
}

const getUniqueValues = (fieldId) => {
  const data = tableStore.currentData
  const values = data.map(item => item[fieldId]).filter(val => val != null)
  return [...new Set(values)].sort()
}

const formatValue = (value, fieldId) => {
  const fieldType = getFieldType(fieldId)
  
  if (fieldType === 'date') {
    return new Date(value).toLocaleDateString('zh-CN')
  }
  
  if (fieldType === 'number') {
    return Number(value).toLocaleString()
  }
  
  return String(value)
}

const isAllSelected = (filter) => {
  const uniqueValues = getUniqueValues(filter.field)
  return filter.selectedValues.length === uniqueValues.length
}

const toggleSelectAll = (filter) => {
  const uniqueValues = getUniqueValues(filter.field)
  
  if (isAllSelected(filter)) {
    filter.selectedValues = []
  } else {
    filter.selectedValues = [...uniqueValues]
  }
  
  updateFilter(filter)
}

const clearAllFilters = () => {
  filters.value.forEach(filter => {
    tableStore.removeFilter(filter.id)
  })
}

const applyFilters = () => {
  // 筛选器已经实时应用，这里可以添加额外的逻辑
  console.log('应用筛选器')
}
</script>

<style scoped>
.filter-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-right: 1px solid #e4e7ed;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.filter-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.filter-item {
  margin: 8px 16px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.filter-field {
  font-weight: 500;
  color: #303133;
}

.filter-content {
  space-y: 8px;
}

.filter-controls {
  margin-bottom: 12px;
}

.filter-values {
  border-top: 1px solid #e4e7ed;
  padding-top: 12px;
}

.values-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #606266;
}

.values-list {
  max-height: 150px;
  overflow-y: auto;
}

.values-list .el-checkbox {
  display: block;
  margin: 4px 0;
  white-space: nowrap;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-state p {
  margin: 8px 0;
  font-size: 14px;
}

.filter-actions {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 8px;
}

.filter-actions .el-button {
  flex: 1;
}
</style>
